package com.xiyou.week02.map;

import java.util.*;

/**
 * 30. 串联所有单词的子串
 *
 * @ClassName：FindSubstring
 * @Author：西柚
 * @Date：2022/1/10 11:42 上午
 * @Versiion：1.0
 */
public class FindSubstring {

    static Map<String, Integer> wordsMap = new HashMap<>();

    /**
     * 输入：s = "barfoothefoobarman", words = ["foo","bar"]
     * 输出：[0,9]
     * 解释：
     * 从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。
     * 输出的顺序不重要, [9,0] 也是有效答案。
     *
     * @param s
     * @param words
     * @return
     */
    public static List<Integer> findSubstring(String s, String[] words) {
        List<Integer> ans = new ArrayList<>();
        if (s.length() == 0 || words.length == 0) {
            return ans;
        }

        int wordLen = words[0].length();
        int len = s.length() - wordLen * words.length;
        List<String> baseList = Arrays.asList(words);
        List<String> wordList ;
        boolean flag;
        for (int i = 0; i <= len; i++) {
            wordList =  new ArrayList<>(baseList);
            flag = true;
            for (int j = 0; j < words.length; j++) {
                if (!flag) {
                    continue;
                }
                int start = i + (j * wordLen);
                int end = i + ((j + 1) * wordLen);
                System.out.println(s.substring(start, end));
                flag = wordList.remove(s.substring(start, end));
            }

            if (flag) {
                ans.add(i);
            }
        }
        return ans;
    }

    private static boolean valid(String str, String[] words) {
        System.out.println("str:" + str);
        int k = words[0].length();
        Map<String, Integer> spliWords = new HashMap<>();
        for (int i = 0; i < str.length(); i += k) {
            System.out.println("i:" + i);
            System.out.println("k:" + k);
            String key = str.substring(i, i + k);
            System.out.println("key:" + key);
            spliWords.getOrDefault((key), 1 + 1);
        }

        return equalsMap(spliWords, wordsMap);
    }

    private static boolean equalsMap(Map<String, Integer> a, Map<String, Integer> b) {
        System.out.println(a.toString());
        System.out.println(b.toString());
        for (Map.Entry<String, Integer> entry : a.entrySet()) {
            if (b.containsKey(entry.getKey()) && b.get(entry.getKey()) != entry.getValue()) {
                return false;
            }
        }
        for (Map.Entry<String, Integer> entry : b.entrySet()) {
            if (a.containsKey(entry.getKey()) && a.get(entry.getKey()) != entry.getValue()) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String s = "barfoothefoobarman";
        String[] words = {"foo", "bar"};

        System.out.println(findSubstring(s, words));
    }
}
